<?php
class system_passport_instance {
	
	public static function getRow($passport) {
		$concept = new system_passport_concept();
		$where = array();
		if(is_numeric($passport) || is_int($passport)) {
			$where = array('id = ?' => intval($passport));
		} elseif(is_string($passport)) {
			$where = array('identity = ?' => trim($passport));
		}
		return $concept->fetch($where);
	}
	
	public static function emailCheck($email) {
		return preg_match('/^[a-zA-Z0-9]{1}[\w\.]+@[\w]+\.[a-zA-Z]{2,10}$/is', $email);
	}
	
	protected static $_instance = null;
	/**
	 * @return system_passport_instance
	 */
	public static function getInstance() {
		if(self::$_instance === null) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	protected $_user = null;
	/**
	 * @return system_user_row
	 */
	public function getUser() {
		if(null === $this->_user && ($pid = intval(self::getInstance()->getSession()->getId())) > 0) {
			$concept = new community_member_concept(system_nav_language::getInstance()->getName());
			$this->_user = $concept->fetch(array('passport.id = ?' => $pid));
			if(!$this->_user) {
				$identity = self::getInstance()->getSession()->getIdentity();
				$nickname = preg_replace('/^([^@]+)@(.*)/i', '$1', $identity);
				$this->_user = $concept->create();
				$this->_user->setId($pid);
				$this->_user->setPassportId($pid);
				$this->_user->setIdentity($identity);
				$this->_user->setEmail($identity);
				$this->_user->setNickname($nickname);
			}
		}
		return $this->_user;
	}
	
	protected $_session = null;
	/**
	 * @return system_passport_session
	 */
	public function getSession() {
		if(null === $this->_session) {
			$this->_session = new system_passport_session();
		}
		return $this->_session;
	}
}
